package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.google.common.collect.Maps;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.system.domain.vo.DailyStatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DrugVerifyMapper;
import com.ruoyi.system.domain.DrugVerify;
import com.ruoyi.system.service.IDrugVerifyService;
import org.springframework.util.CollectionUtils;

/**
 * 药品审核Service业务层处理
 * 
 * @author wmb
 * @date 2020-08-27
 */
@Service
public class DrugVerifyServiceImpl implements IDrugVerifyService 
{
    @Autowired
    private DrugVerifyMapper drugVerifyMapper;

    /**
     * 查询药品审核
     * 
     * @param id 药品审核ID
     * @return 药品审核
     */
    @Override
    public DrugVerify selectDrugVerifyById(Long id)
    {
        return drugVerifyMapper.selectDrugVerifyById(id);
    }

    /**
     * 查询药品审核列表
     * 
     * @param drugVerify 药品审核
     * @return 药品审核
     */
    @Override
    public List<DrugVerify> selectDrugVerifyList(DrugVerify drugVerify)
    {
        return drugVerifyMapper.selectDrugVerifyList(drugVerify);
    }

    /**
     * 新增药品审核
     * 
     * @param drugVerify 药品审核
     * @return 结果
     */
    @Override
    public int insertDrugVerify(DrugVerify drugVerify)
    {
        return drugVerifyMapper.insertDrugVerify(drugVerify);
    }

    @Override
    public Map<String, List<DailyStatVo>> dailyStat(Map<String, Object> map) {

        List<Map<String,Object>> stat = drugVerifyMapper.dailyStat(map);

        Map<String,List<Map<String,Object>>> result = stat.stream().collect(Collectors.groupingBy(s -> (String)s.get("verify")));

        Map<String, List<DailyStatVo>> daily = Maps.newHashMap();
        //根据状态分类 0 未处理，1通过 2不通过
        result.forEach((verify,statusList)->{

            List<DailyStatVo> data = completeData(LocalDate.now().minusDays(30),LocalDate.now(),statusList);
            String key = "";
            if("0".equals(verify)){
                key = "unHandle";
            }else if("1".equals(verify)){
                key = "pass";
            }else if("2".equals(verify)){
                key = "noPass";
            }
            daily.put(key,completeData(LocalDate.now().minusDays(30),LocalDate.now(),statusList));
        });
        //result.keySet();
        return daily;
    }

    /**
     * 补全数据
     *
     * @param preDate 开始日期
     * @param endDate 截止日期
     * @param oldList 未补全的列表
     * @return 补全后的列表
     */
    private List<DailyStatVo> completeData(LocalDate preDate, LocalDate endDate, List<Map<String,Object>> oldList) {
        List<DailyStatVo> newList = new ArrayList<>();
        if (CollectionUtils.isEmpty(oldList)) {
            return newList;
        }
        //间隔的日期列表
        List<LocalDate> dates = this.getRangeDays(preDate, endDate);

        Map<String, Object> map = oldList.stream()
                .collect(Collectors.toMap(s -> (String)s.get("groupdate"), s -> s.get("verifyCount")));

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        dates.forEach(c -> {
            Map<String,Object> date = Maps.newHashMap();
            String d =  c.format(fmt);
            if (!map.containsKey(d)) {
                map.put(d, BigDecimal.ZERO);
            }
        });
        newList = map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey()))
                .map(e -> new DailyStatVo(e.getKey(), Integer.parseInt(e.getValue().toString()))).collect(Collectors.toList());

        return newList;
    }

    /**
     * 获取间隔的日期列表
     *
     * @param preDate 开始日期
     * @param endDate 截止日期
     * @return
     */
    private List<LocalDate> getRangeDays(LocalDate preDate, LocalDate endDate) {
        List<LocalDate> dates = new ArrayList<>();
        //间隔的天数
        long betweenDays = ChronoUnit.DAYS.between(preDate, endDate);
        if (betweenDays < 1) {
            //开始日期<=截止日期
            return dates;
        }
        //创建一个从开始日期、每次加一天的无限流，限制到截止日期为止
        Stream.iterate(preDate, c -> c.plusDays(1))
                .limit(betweenDays + 1)
                .forEach(dates::add);
        return dates;
    }
    /**
     * 修改药品审核
     * 
     * @param drugVerify 药品审核
     * @return 结果
     */
    @Override
    public int updateDrugVerify(DrugVerify drugVerify)
    {
        return drugVerifyMapper.updateDrugVerify(drugVerify);
    }

    /**
     * 批量删除药品审核
     * 
     * @param ids 需要删除的药品审核ID
     * @return 结果
     */
    @Override
    public int deleteDrugVerifyByIds(Long[] ids)
    {
        return drugVerifyMapper.deleteDrugVerifyByIds(ids);
    }

    /**
     * 删除药品审核信息
     * 
     * @param id 药品审核ID
     * @return 结果
     */
    @Override
    public int deleteDrugVerifyById(Long id)
    {
        return drugVerifyMapper.deleteDrugVerifyById(id);
    }
}
